package com.kvest.mobile_newspaper.network;

import java.util.Enumeration;
import java.util.Hashtable;

import com.kvest.mobile_newspaper.core.ArticlesManager;
import com.kvest.mobile_newspaper.core.Parser;
import com.kvest.mobile_newspaper.datamodel.Article;
import com.kvest.mobile_newspaper.datamodel.ElementsContainer;
import com.kvest.mobile_newspaper.datamodel.ProxyArticle;
import com.kvest.mobile_newspaper.datastorage.ImageStorage;
import com.kvest.mobile_newspaper.network.base.HTTPGetRequest;
import com.kvest.mobile_newspaper.network.base.HTTPRequestResult;
import com.kvest.mobile_newspaper.network.base.ImageLoader;

public class GetClubRequest implements Parser.ParserNotifier
{
	public static final String NULL_PARENT_VALUE = "";
	
	private String clubId;
	private String parent;
	
	private HTTPGetRequest request; 
	private GetClubResult resultListener;
	
	private Parser parser;
    private ElementsContainer resultElement;
    private boolean needLoadArticles;
    private Hashtable<String, ElementsContainer> articles;
    private boolean interrupted;
    private boolean allArticlesLoaded;
	
	public GetClubRequest(String clubId, String parent, GetClubResult resultListener)
	{
        this.interrupted = false;
		this.clubId = clubId;
		this.parent = parent;
		this.resultListener = resultListener;
		
		this.parser = new Parser();
		this.parser.setParserNotifier(this);
		this.needLoadArticles = true;
		this.articles = new Hashtable<String, ElementsContainer>();
	}
	
	public void sendRequest()
    {
		//������ ������
        articles.clear();
        
        //���������� �������� � ����������
        allArticlesLoaded = true;
        
		request = new HTTPGetRequest(Urls.GET_CLUB_URL + "?" + Urls.CLUB_ID_PARAM + "=" + clubId + 
				 					(parent.equals(NULL_PARENT_VALUE) ? "" : "&" + Urls.PARENT_PARAM + "=" + parent));
		request.setResultListener(new HTTPRequestResult() 
		{
			public void httResponce(int code, String result) 
			{
				//������������ �������
                if (code == HTTPRequestResult.RESULT_OK)
                {
                    resultElement = parser.parseElementsContainer(result);

                    //���� �� ���������� ������ - �� ������ ��� ���������
                    if (resultElement == null)
                    {
                        resultListener.clubResult(GetClubResult.FATAL_ERROR_RESULT, null, clubId);
                    }
                    else
                    {
                        //������ ������
                        loadArticles();
                    }
                }
                else if (code == HTTPRequestResult.RESULT_ERROR)
                {
                    resultListener.clubResult(GetClubResult.FATAL_ERROR_RESULT, null, clubId);
                }
				
			}
		});
		request.start();
    }
	
	public void interrupt()
    {
    	if (request != null)
    	{
    		request.interrupt();
    	}
    	interrupted = true;
    }
	
	private void loadArticles()
	{
		//���� ������ ��� ������� - �������
        if (interrupted)
        {
            return;
        }
        
       
        Enumeration<String> key =  articles.keys();
        if (key.hasMoreElements())
        {
        	request = new HTTPGetRequest(Urls.GET_ARTICLE_URL + "?" + Urls.ARTICLE_ID_PARAM + "=" + key.nextElement() + '&' + Urls.ARTICLE_IMG_DETAIL + '&' + Urls.ARTICLE_AS_HTML);
        	request.setResultListener(new HTTPRequestResult() 
    		{
    			public void httResponce(int code, String result) 
    			{
    				//���� ������ ��� ������� - �������
                    if (interrupted)
                    {
                        return;
                    }
                    
                    //������������ �������
                    if (code == HTTPRequestResult.RESULT_OK)
                    {
                    	Article article = parser.parseArticle(result);
                    	if (article != null)
                        {
                            //��������� ������
                            ArticlesManager.getManager().addArticle(article);
                            
                            ElementsContainer parent = (ElementsContainer)articles.get(article.getId());
                            if (parent != null)
                            {
                                ProxyArticle proxyArticle = new ProxyArticle(article); 
                                parent.addChild(proxyArticle);
                            }
                            
                            //������� �� ������� �� ��������
                            articles.remove(article.getId());
                        }
                        else
                        {
                            allArticlesLoaded = false;
                            
                            //������� ������ ������� � ���������
                            removeFirsArticleInArticles();
                        }
                    }
                    else
                    {
                    	allArticlesLoaded = false;
                        
                        //������� ������ ������� � ���������
                        removeFirsArticleInArticles();
                    }
                    
                    //������ ��������� ������
                    loadArticles();
    			}
    		});
        	request.start();
        }
        else
        {
        	//���� ��� ��������� - ���������� ���������, ������������ ��� ��������������
            resultElement.sortArticles();
            resultListener.clubResult((allArticlesLoaded ? GetClubResult.OK_RESULT : GetClubResult.SOME_ERROR_RESULT), resultElement, clubId);
        }
		
	}
	
	private void removeFirsArticleInArticles()
    {
		Enumeration<String> key =  articles.keys();
        if (key.hasMoreElements())
        {
            articles.remove(key.nextElement());
        }
    }
	
	public void setArticleID(String articleID, ElementsContainer parent) 
	{
		if (articleID != null && (!articleID.equals("")) && parent != null && needLoadArticles)
        {
            //���� ���� ������ - �� ������ �� ��������
            Article article = ArticlesManager.getManager().getArticle(articleID); 
            if (article != null)
            {
                ProxyArticle proxyArticle = new ProxyArticle(article); 
                parent.addChild(proxyArticle);
            }
            else
            {
                articles.put(articleID, parent);
            }
        }
	}

	public void setImageForArticle(String link, Article article) 
	{
		if (link != null && !link.equals("") && article != null)
        {
            //��������� ��������
            loadPicture(link, article);
        }
	}
	
	private void loadPicture(String link, final Article article)
	{
		//���� ������ ��� ������� - �������
        if (interrupted)
        {
            return;
        }
        
		article.setDetailImage(ImageLoader.loadImage(link));
	}
	
	public void setImagesInHtml(String articleID, String links[])
	{		
		//������ ������ ��������
		for (int i = 0; i < links.length; ++i)
		{
			//���� ������ ��� ������� - �������
			if (interrupted)
			{
				return;
			}
			
			//��������� �������
			ImageStorage.saveImageForArticle(articleID, links[i], ImageLoader.loadImage(links[i]));
		}
	}
	
	public boolean isNeedLoadArticles()
    {
        return needLoadArticles;
    }

    public void setNeedLoadArticles(boolean needLoadArticles)
    {
        this.needLoadArticles = needLoadArticles;
    }
	
	public interface GetClubResult
    {
        public static final int OK_RESULT = 0;
        public static final int SOME_ERROR_RESULT = 1;
        public static final int FATAL_ERROR_RESULT = 2;

        public abstract void clubResult(int resultType, ElementsContainer club, String clubParentId);
    }
}
